package com.cy.milktea.service.impl;

import com.cy.milktea.common.annotation.SetUserAndTime;
import com.cy.milktea.mapper.RoleMapper;
import com.cy.milktea.mapper.RoleMenuMapper;
import com.cy.milktea.mapper.UserMapper;
import com.cy.milktea.pojo.Menu;
import com.cy.milktea.pojo.Role;
import com.cy.milktea.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private RoleMenuMapper roleMenuMapper;

    @SetUserAndTime
    @Transactional
    @Override
    public int add(Role role) {

        try {
            //将role基本信息存入role表中,roleName是唯一约束,当重复时会抛异常
            roleMapper.insert(role);
        } catch (Exception e) {
            throw new RuntimeException("角色名称重复!");
        }
        //通过roleName获取数据库自增id
        int roleId = roleMapper.selectIdByRoleName(role.getName());
        if (role.getMenuIds().size() != 0) {
            roleMenuMapper.insert(roleId, role.getMenuIds());
        }
        return 1;
    }

    @Transactional
    @Override
    public int delete(Integer id) {
        //删除前先判断user中是否还含有该角色
        int count = userMapper.selectCountRoleId(id);
        if (count == 0) {
            //删除中间表中含有roleId的行
            roleMenuMapper.deleteByRoleId(id);
            return roleMapper.delete(id);
        }
        return -1;
    }

    @SetUserAndTime(value = "modify")
    @Transactional
    @Override
    public int update(Role role) {
        //判断是否包含角色权限的修改
        if (role.getMenuIds() != null) {
            //删除tb_role_menu中间表中当前roleId的行
            roleMenuMapper.deleteByRoleId(role.getId());
            //添加新的权限
            roleMenuMapper.insert(role.getId(), role.getMenuIds());
        }
        //更新基本信息
        return roleMapper.update(role);
    }

    @Override
    public List<Role> queryAllWithMenus(Integer status) {
        List<Role> roles = roleMapper.selectAllWithMenus(status);
        //获取每个角色的菜单id列表
        for (Role role : roles) {
            role.setMenuLastChildIds(Menu.getLastChildMenuIds(role.getMenus()));
            List<Menu> menus = role.getMenus();
            List<Integer> menuIds = new ArrayList<>();
            for (Menu menu : menus) {
                menuIds.add(menu.getId());
            }
            role.setMenuIds(menuIds);
        }
        return roles;
    }

    @Override
    public List<Role> queryAllWithMenuIds() {
        List<Role> roles = roleMapper.selectAllWithMenuIds();
        return roles;
    }
}
